alertify.set({
				labels : {
					ok     : "确定",
					cancel : "取消"
				},
				delay : 5000,
				buttonReverse : false,
				buttonFocus   : "ok"
			});

$(function(){
	var load_dtd= $.Deferred();
	$.when(getStore(load_dtd)).done(function(){
		getGroup(load_dtd);
	});
	$("#pokerGroupList").on('click','.list-group-item',function(){
		$("#orderBtn").show();
		$(this).append($("#orderBtn"));
		$(this).addClass("active");
		$(this).siblings().removeClass("active");
		if(sys.storeFlag){
			reset();
			var groupData=$(this).data("baseData");
			if(groupData){
				loadPokerImage(groupData["pokerData"]);
				$("#groupNo").val(groupData["pokerGroupNo"]);
				$("#groupNo").data("id",groupData["pokerGroupId"]);//放入值
				$("#groupDesc").val(groupData["pokerGroupDesc"]);
			}
		}
	});
	$('#pokerGroupList').on('click',".order-up",function(e){
		var $needMove = $(this).parents("li");
		var $preNode=$(this).parents("li").prev();
		//$preNode.trigger("mouseover");
		$preNode.before($needMove);
		
	});
	$('#pokerGroupList').on('click',".order-top",function(e){
		var $needMove = $(this).parents("li");
		var $preNode=$(this).parents("li").siblings().first();
		$preNode.trigger("mouseover");
		$preNode.before($needMove);
		$("#pokerGroupList").animate({scrollTop:0},'fast');
	});
	
	$("#storeSelect").on("change",function(e){
		$("#orderBtn").hide();
		$("#pokerGroupList").parent().append($("#orderBtn"));
		$(".list-group-item").remove();
		getGroup(load_dtd);
	});
	$('#pokerGroupList').on('click',".order-edit",function(e){
		alertify.log("请前往发牌界面进行编辑操作","", 2500);
	});
	$('#pokerGroupList').on('click',".order-delete",function(e){
		delGroup();
	});
	
	$(".pokerSelect").on("click",function(e){
		$(this).attr("oldVal",$(this).val());
	});
	$(".pokerSelect").on("change",function(e){
		var changeSelect=$(this);
		$(".pokerSelect option[value="+$(this).val()+"]:selected").parent().each(function(i,select){
			if(select!=changeSelect[0]){
				$(select).val($(changeSelect).attr("oldVal"));
			}
		});
	});
});

function saveGroup(){
	var groupNo=$("#groupNo").val();
	var storeId=$("#storeSelect").val();
	var groupDesc=$("#groupDesc").val();
	if(!groupNo || !storeId || !groupDesc){
		alertify.error("请完整牌组信息");
		return;
	}
	if(groupNo.length>9 || groupDesc.length>100){
		alertify.error("字符超出限制");
		return;
	}
	var pokerData={};
	var isRight=false;
	$(".pokerClass").each(function(i,obj){
		var data=$(obj).data("dataPoker");
		if(!data || data.length<13){
			isRight=true;
			return;
		}
		pokerData[$(obj).attr("id")]=data;
	});
	if(isRight){
		alertify.error("请完整牌组信息");
		return;
	}
	var roomId=$("#roomIdSpan").html()||"";
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/saveGroup?groupNo="+$("#groupNo").val()
						+"&storeId="+$("#storeSelect").val()
						+"&roomId="+roomId
						+"&groupDesc="+$("#groupDesc").val()+"&groupId="
						+($("#groupNo").data("id")?$("#groupNo").data("id"):""),
		data:JSON.stringify(pokerData),
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && !data.error){
				alertify.alert("保存成功！");
				$("#orderBtn").hide();
				$("#pokerGroupList").parent().append($("#orderBtn"));
				$(".list-group-item").remove();
				load_dtd=$.Deferred();
				$.when(getGroup(load_dtd)).done(function(){
					if($("#groupNo").data("id")){
						$("#"+$("#groupNo").data("id")).trigger("click");
					}
				});
			}
		}
	});
}
/**
 * 查询牌组
 */
function getGroup(load_dtd){
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/getGroup?storeId="+$("#storeSelect").val(),
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && data.data){
				$("#noDataSpan").hide();
				$(data.data).each(function(i,group){
					var $html=$('<li  class="list-group-item" id='+group["pokerGroupId"]+'>'+group["pokerGroupName"]+'('+group["pokerGroupDesc"]+')'+'</li>');
					$html.data("baseData",group);
					$("#pokerGroupList").append($html);
				})
				$("#storeSelect").data("groupData",data.data);
			}else{
				$("#noDataSpan").show();
			}
			load_dtd.resolve();
		}
	});
	return load_dtd;
}
/**
 * 查询牌库
 */
function getStore(load_dtd){
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokerStore/getStore",
		dataType:"json",
		data:{},
		contentType:"application/json",
		success: function(data) {
			if(data && data.data){
				$(data.data).each(function(i,store){
					var $html=$('<option value="'+store['pokerStoreId']+'">'+store['pokerStoreName']+'</option>');
					$html.data("baseData",store);
					$("#storeSelect").append($html);
				})
			}
			load_dtd.resolve();
		}
	});
	return load_dtd;
}

function loadPokerImage(data){
	for(var i=1;i<5;i++){
		$(data["poker"+i]).each(function(j,poker){
			var path=sys.context+"image/pokerFace/"+poker["prefix"]+poker["indexVal"]+".png";
			var $img=$("<img class='rePokerImg' ondragstart='return false' onclick='delPoker(this)' src="+path+" style='height:50px;cursor:pointer;'>");
			$img.data("evelData",poker);
			$("#poker"+i).next().append($img);
			changeCss($(".poker[src='"+path+"']"));
		});
		$("#poker"+i).data("dataPoker",$.extend([],data["poker"+i]));
		
	}
}
function changeCss(el){
	$(el).parent().css("background-color","#000");
	$(el).css("opacity","0.4");
	$(el).data("disabled",true);
}

/**
 * 重置
 */
function reset(){
	//清除数据
	$(".pokerClass").removeData();
	$(".rePoker").html("");
	$(".poker").css("opacity","1").data("disabled",false);
	$(".poker").parent().css("background-color","#fff");
	$("#groupNo").val("");
	$("#groupNo").removeData();
	$("#groupDesc").val("");
}
/**
 * 删除牌组
 */
function delGroup(){
	alertify.set({ labels: { ok: "确定", cancel: "取消" } });
	alertify.confirm("确定删除该牌组么？", function (e) {
		if (e) {
			var groupId=$(".list-group-item.active").data("baseData")["pokerGroupId"];
			if(!groupId)return;
			$.post(sys.contextPath+"/pokermgr/delGroup?pokerGroupId="+groupId,{},function(data){
				if(data && !data.data){
					alertify.success("删除成功！");
					var dtd= $.Deferred();
					$.when(resetGroupList()).done(function(){						
						getGroup(dtd);
					});
				}else if(data.msg){
					alertify.error(data.msg);
				}
			});
		} else {
			alertify.error("您取消了删除");
		}
	});
	
}
/**
 * 添加牌库
 */
function addStore(){
	var storeNo=$("#storeNo").val();
	if(!storeNo){
		alertify.error("请输入新牌库编号！");
		return;
	}
	if(storeNo.length>16){
		alertify.error("字符超出限制！");
		return;
	}
	var pokerStore={"pokerStoreNo":storeNo,"pokerStoreName":"牌库"+storeNo};
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokerStore/addStore",
		data:JSON.stringify(pokerStore),
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && !data.error){
				alertify.success("添加成功！");
				$("#storeSelect").html("");
				getStore();
			}else if(data.msg){
				alertify.error(data.msg);
			}
		}
	});
}

function resetGroupList(dtd){
	$("#orderBtn").hide();
	$("#pokerGroupList").parent().append($("#orderBtn"));
	$(".list-group-item").remove();
	return dtd;
}

/**
 * 加载游戏信息
 */
function loadPlayInfo(){
	sys.loadGameData=false;
	var playerId=$("#roomId").val()
	if(!playerId){
		alertify.error("请输入玩家ID");
		return;
	}
	window.clearInterval(sys.timer);
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/getPlayInfo?playerId="+playerId,
		data:{},
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && data.data && data.data.length>0){
				var roomId=data.data[0]["roomId"];
				$("#roomIdSpan").html(roomId);
				$(".userInput").val("");
				$(".userInput").attr("dataFlag",true);
				$(".userInput").each(function(i,obj){
					var player=data.data[i];
					if(player){
						$(obj).val("玩家"+player["name"]+":"+player["id"]);
						$(obj).attr("dataFlag",true);
						$(obj).data("userId",player["id"]);
					}else{
						$(obj).data("userId",i);
					}
				});
				timerCheck(1);
				//sys.timer=setInterval("timerCheck()",5000);
			}else if(data){
				if(!data.msg || data.msg==""){
					data.msg="没有查询到该玩家的房间";
				}
				alertify.error(data.msg);
				timerCheck(1);
				var data={"data":[{"name":"模拟玩家A","id":"1234","roomId":"339654"},
				                  {"name":"模拟玩家B","id":"1235","roomId":"339654"},
				                  {"name":"模拟玩家C","id":"1236","roomId":"339654"},
				                  {"name":"模拟玩家D","id":"1237","roomId":"339654"}]}
				if(data && data.data){
					var roomId=data.data[0]["roomId"];
					$("#roomIdSpan").html(roomId);
					$(data.data).each(function(i,player){
						$($(".userInput")[i]).val(player["name"]+":"+player["id"]);
						$($(".userInput")[i]).attr("dataFlag",true);
						$($(".userInput")[i]).data("userId",player["id"]);
					});
				}
			}
		}
	});
	
}

function timerCheck(flag){
	var roomId=$("#roomIdSpan").html();
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/getAlreadyInfo?roomId="+roomId,
		data:{},
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && data.data && !data.error){
				if(flag==1){
					alertify.confirm("查询到房间号"+roomId+"已设置发牌数据，是否加载？",function(e){
						if(e){
							sys.timer=setInterval("timerCheck(2)",2000);
							alertify.log("正在加载游戏数据");
						}else{
							return;
						}
					});
				}else{
					$("#noDataSpan").hide();
					if(data.data.length==$("#storeSelect").data("groupData").length){
						return;
					}
					if(data.data.length!=$("#storeSelect").data("groupData").length){
						alertify.success("房间"+roomId+"已发出牌组数据");
					}
					
					var dtd= $.Deferred();
					resetGroupList(dtd);
					$(data.data).each(function(i,group){
						var $html=$('<li  class="list-group-item" id='+group["pokerGroupId"]+'>'+group["pokerGroupName"]+'('+group["pokerGroupDesc"]+')'+'</li>');
						$html.data("baseData",group);
						$("#pokerGroupList").append($html);
					});
					$("#storeSelect").prop("disabled",true);
					$("#storeSelect").data("groupData",data.data);
					sys.loadGameData=true;
				}
			}else{
				window.clearInterval(sys.timer);
				if(data.msg && flag!=1){
					alertify.success(data.msg);
					resetGroupList();
					$("#noDataSpan").show();
					return;
				}
				$("#noDataSpan").hide();
			}
		}
	});
}
/**
 * 加载玩家
 */
function loadPlayer(){
	var data={"cmd":"selectPlayer","args":[$("#roomId").val()]};
	$.ajax({
		type: "POST",
		url:"http://192.168.3.46:9002/",
		data:JSON.stringify(data),
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && !data.error){
				alertify.success(data.msg);
			}else{
				alertify.error(data.msg);
			}
		}
	});
}
/**
 * 提交发送数据
 */
function saveSendData(){
	var group=[],roomId=$("#roomIdSpan").html()||"";
	if(!roomId){
		alertify.alert("请先选定房间");
		return;
	}
	$("#pokerGroupList li").each(function(i,li){
		group.push({"pokerGroupId":$(li).attr("id")});
	});
	var sendData={"user":getUserClass(),"roomId":roomId}
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/commitData",
		data:JSON.stringify(sendData),
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			$.ajax({
				type: "POST",
				url:sys.contextPath+"/pokermgr/commitPoker?roomId="+roomId,
				data:JSON.stringify(group),
				dataType:"json",
				contentType:"application/json",
				success: function(data) {
					if(data){
						alertify.success(data.msg);
						alertify.confirm("是否加载该房间发牌数据？",function(e){
							if(e){
								sys.timer=setInterval("timerCheck(2)",2000);
								alertify.log("正在加载游戏数据");
							}else{
								return;
							}
						});
					}else{
						alertify.error(data.msg);
					}
				}
			});
		}
	});
}
function getUserClass(){
	var data={};
	$(".userInput").each(function(i,user){
		if($(user).attr("dataFlag")){
			var userId=$(user).data("userId");
			var userClass=$(user).parents(".row").children().children(".pokerSelect").val();
			data[userId]=userClass;
		}
	});
	return data;
}

function closeLoadGameData(){
	var roomId=$("#roomIdSpan").html()||"";
	if(!roomId){
		alertify.confirm("您没有选择关闭房间，是否关闭所有？",function(e){
			if(e){
				closeAllRoomData();
			}else{
				alertify.log("您取消了关闭所有");
			}
		});
		return;
	}
	sys.loadGameData=false;
	$("#storeSelect").prop("disabled",false);
	window.clearInterval(sys.timer);
	reset();
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/closeRoonSend?roomId="+roomId,
		data:{},
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && !data.error){
				alertify.success(data.msg);
				if(data.data && data.data.length>0){
					alertify.confirm("检测到后台仍有"+data.data.length+"个房间正在使用发牌控制\u000d是否关闭？",function(e){
						if(e){
							closeAllRoomData();
						}else{
							alertify.log("您取消了关闭所有");
							return;
						}
					});
				}
			}else{
				alertify.error(data.msg);
			}
		}
	});
}
function closeAllRoomData(){
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokermgr/closeAllRoomData",
		data:{},
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && !data.error){
				alertify.success(data.msg);
			}else{
				alertify.error(data.msg);
			}
		}
	});
}
function delStore(){
	var storeId=$("#storeSelect").val()||"";
	$.ajax({
		type: "POST",
		url:sys.contextPath+"/pokerStore/delStore?storeId="+storeId,
		data:{},
		dataType:"json",
		contentType:"application/json",
		success: function(data) {
			if(data && !data.error){
				alertify.success(data.msg);
				$("#storeSelect").html("");
				$("#orderBtn").hide();
				$("#pokerGroupList").parent().append($("#orderBtn"));
				$(".list-group-item").remove();
				var dtd= $.Deferred();
				$.when(getStore(dtd)).done(function(){
					getGroup(dtd);
				});
			}else{
				alertify.error(data.msg);
			}
		}
	});
}